using HarmonyLib;
using RimWorld;
using System.Reflection;
using Verse;
using System.Reflection.Emit;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System;
using Verse.AI;
using RimWorld.Planet;

namespace RimZombieGirl
{
    public static class FuelPatcher
    {
        [HarmonyPatch(typeof(CompRefuelable), "PostDraw")]
        public static class Patch_CompRefuelable_PostDraw
        {
            [HarmonyPrefix]
            public static bool Prefix(CompRefuelable __instance)
            {
                if (__instance.parent?.def?.defName != "RI_ZombieTransformationCoffin")
                    return true;
                Material FuelBarFilledMat = SolidColorMaterials.SimpleSolidColorMaterial(new Color(0.5f, 1.1f, 1.07f), false);
                if (!__instance.allowAutoRefuel)
                {
                    __instance.parent.Map.overlayDrawer.DrawOverlay(__instance.parent, OverlayTypes.ForbiddenRefuel);
                }
                else if (!__instance.HasFuel && __instance.Props.drawOutOfFuelOverlay)
                {
                    __instance.parent.Map.overlayDrawer.DrawOverlay(__instance.parent, OverlayTypes.OutOfFuel);
                }

                if (__instance.Props.drawFuelGaugeInMap)
                {
                    FieldInfo fuelBarSizeField = typeof(CompRefuelable).GetField("FuelBarSize", BindingFlags.NonPublic | BindingFlags.Static);
                    FieldInfo fuelBarUnfilledMatField = typeof(CompRefuelable).GetField("FuelBarUnfilledMat", BindingFlags.NonPublic | BindingFlags.Static);

                    Vector2 fuelBarSize = (Vector2)fuelBarSizeField.GetValue(null);
                    Material unfilledMat = (Material)fuelBarUnfilledMatField.GetValue(null);

                    GenDraw.FillableBarRequest r = default;
                    r.center = __instance.parent.DrawPos + Vector3.up * 0.1f;
                    r.size = fuelBarSize;
                    r.fillPercent = __instance.FuelPercentOfMax;

                    // 血红色
                    r.filledMat = FuelBarFilledMat;
                    r.unfilledMat = unfilledMat;
                    r.margin = 0.15f;

                    Rot4 rotation = __instance.parent.Rotation;
                    rotation.Rotate(RotationDirection.Clockwise);
                    r.rotation = rotation;

                    GenDraw.DrawFillableBar(r);
                }

                return false; // 阻止原方法
            }
        }
    }
}